﻿using DataModels.Models;
using DataModels.Models.Context;
using GenericTools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services.Protocols;

namespace IQWebServices
{
    /// <summary>
    /// Authentication header passed to the user of the web service
    /// </summary>
    public class AuthenticationHeader : SoapHeader
    {
        /// <summary>
        /// Username
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// Password hash.
        /// The hash is generated by taking the combination of Username and password separated by |
        /// Username|Password
        /// </summary>
        public string PasswordHash { get; set; }

        public User GetUserProfile()
        {
            if (string.IsNullOrWhiteSpace(Username)) return null;
            if (string.IsNullOrWhiteSpace(PasswordHash)) return null;

            using (var db = new IQSMS_TestDBContext())
            {
                db.Configuration.ProxyCreationEnabled = false;
                User user = (from u in db.Users.Include("AccessLevel")
                             where u.Username == Username
                             select u).FirstOrDefault();
                if (user == null) return null;
                else
                {
                    // Now that the provided username does exist. The second step will be
                    // proving the supplied password hash. 
                    // The hash is supposed to be created by combining the username and password
                    // by seperating them by |. After getting that combined text its hash should
                    // match with the one provided by request. Otherwise we don't trust this guy!!!

                    string plainTextPassword = DataTransformation.Decrypt(user.Password);
                    string magicText = Username + "|" + plainTextPassword;
                    string targetHash = DataTransformation.Hash(magicText);
                    
                    if (targetHash == PasswordHash) return user;
                    else return null;
                }                            
            }
        }
    }
}